package net.oschina.arvin.dbjava.type;

import net.oschina.arvin.dbjava.model.Column;

/**
 * <pre>
 *     参考地址： https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-type-conversions.html
 *
 *     以下情况会被认为是Int类型：
 *     1. SMALLINT
 *     2. MEDIUMINT
 *     3. TINYINT & len > 1
 *     4. INT & INTEGER 并且 unsigned = false
 * </pre>
 *
 * @author Arvin
 * @time 2017/9/29 9:52
 */
public class IntDBJavaTypeConverter implements DBJavaTypeConverter {

    @Override
    public Class<?> convertToJavaType(Column column, boolean toBoolForLenOneNumber, boolean useUtilDate, boolean wrapMode) {
        String dataType = column.getDataType().toUpperCase();
        boolean isIntType = false;
        if ("SMALLINT".equals(dataType) || "MEDIUMINT".equals(dataType)) {
            isIntType = true;
        } else if ("TINYINT".equals(dataType)) {
            if (!toBoolForLenOneNumber) { // 长度为1的也不进行转成boolean
                isIntType = true;
            } else { // 如果长度为1 则不算int
                if (column.getColumnLen() != null && column.getColumnLen() > 1) {
                    isIntType = true;
                }
            }
        } else if ("INT".equals(dataType) || "INTEGER".equals(dataType) && !column.isUnsigned()) {
            isIntType = true;
        }
        if (isIntType) {
            return wrapMode ? Integer.class : int.class;
        }

        return null;
    }

    @Override
    public String convertToDBColumnType(Class<?> javaType) {
        if (javaType == int.class || javaType == Integer.class) {
            return "INT(11)";
        }
        return null;
    }
}
